package com.qianxun.watchdog.script;


import com.qianxun.framework.util.FileUtil;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * 脚本执行器
 * @author: huwei
 * @date: 2020/10/16 11:32
 * @version: 1.0.0
 */
public class ScriptExecutor {
    private ScriptExecutor(){}
    public static ScriptExecutor getInstance(){
        return Holder.INSTANCE;
    }

    public byte[] run(String command) throws Exception{
        String home = "/application/temp/runtime/script/";
        try {
            new File(home).mkdirs();
        }catch (Exception e){}
        String scriptPath = home +  UUID.randomUUID().toString().replace("-","").concat(".sh");
        FileUtil.write(scriptPath ,command.getBytes());

        //执行脚本权限赋值
        new ProcessBuilder("/bin/chmod" ,"755" ,scriptPath).start().waitFor();
        //执行脚本
        Process process = Runtime.getRuntime().exec("/bin/sh " + scriptPath);
        process.waitFor();
        //读取返回数据
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        InputStream is = process.getInputStream();
        boolean error = false;
        try {
            bos.write(FileUtil.read(is));
        } catch (IOException e) {
            try {
                bos.write(FileUtil.read(process.getErrorStream()));
            } catch (IOException ex) {
                error = true;
            }
        }
        //删除临时脚本
        new ProcessBuilder("/bin/rm" ,"-rf" ,scriptPath).start().waitFor();

        if(error){
            throw new Exception("脚本执行错误");
        }
        return bos.toByteArray();
    }

    private static class Holder {
        static final ScriptExecutor INSTANCE = new ScriptExecutor();
    }
}
